package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.query.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService ;
    @Autowired
    private IPermissionService permissionService ;

    @RequestMapping("/list")
    //@RequiredPermission(name="角色列表",expression = "role:list")
    @RequiresPermissions(value ={"role:list","角色列表"},logical = Logical.OR )
    public String list(Model model , QueryObject qo){
        PageInfo<Role> pageInfo = roleService.query(qo);
        model.addAttribute("pageInfo",pageInfo );

        return "/role/list";
    }
    @RequestMapping("/delete")
    @ResponseBody
    //@RequiredPermission(name="角色删除",expression = "role:delete")
    @RequiresPermissions(value ={"role:delete","角色删除"},logical = Logical.OR )
    public JsonResult delete(Long id){
        try {
            roleService.delete(id);
            return new JsonResult();
        } catch(Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"操作失败");
        }
    }
    @RequestMapping("/input")
    @RequiredPermission(name="角色编辑",expression = "role:input")
    public String input(Model model , Long id){
        List<Permission> permissions = permissionService.selectAll();
        model.addAttribute("permissions",permissions );
        if (id != null) {
            Role role = roleService.selectOne(id);
            //System.out.println(role);
            model.addAttribute("role",role );
        }
        return "/role/input";
    }
    @RequestMapping("/saveOrUpdate")

    public String saveOrUpdate(Role role, Long[] ids){
        Long id = role.getId();
        if (id != null) {
            roleService.update(role, ids);
        }else{
            roleService.insert(role,ids);
        }
        return "redirect:/role/list.do";
    }

}
